<template>
  <div class="profile-container">
    <!-- 用户订阅信息组件 -->
    <UserSubscriptionInfo />
    
    <a-row :gutter="[24, 24]">
      <a-col :xs="24" :md="8">
        <a-card class="profile-card">
          <div class="profile-header">
            <a-avatar :size="80" icon="user" />
            <h2>{{ userFullName }}</h2>
            <p>{{ user?.email }}</p>
            <p v-if="currentSubscription">
              <a-tag :color="getSubscriptionColor()">
                {{ currentSubscription.pricing_plan.name }}会员
              </a-tag>
              <span>剩余 {{ daysRemaining }} 天</span>
            </p>
            <p v-else>
              <a-tag color="default">免费用户</a-tag>
            </p>
          </div>
          
          <a-divider />
          
          <div class="profile-stats">
            <div class="stat-item">
              <p class="stat-value">{{ promptStats?.total_prompts || 0 }}</p>
              <p class="stat-label">提示词总数</p>
            </div>
            <div class="stat-item">
              <p class="stat-value">{{ promptStats?.public_prompts || 0 }}</p>
              <p class="stat-label">公开提示词</p>
            </div>
            <div class="stat-item">
              <p class="stat-value">{{ promptStats?.private_prompts || 0 }}</p>
              <p class="stat-label">私有提示词</p>
            </div>
          </div>
          
          <a-divider />
          
          <div class="profile-actions">
            <a-button type="primary" block @click="router.push('/pricing')">
              {{ currentSubscription ? '升级会员' : '立即订阅' }}
            </a-button>
          </div>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :md="16">
        <a-tabs v-model:activeKey="activeTab">
          <a-tab-pane key="account" tab="账号设置">
            <a-card>
              <a-form
                :model="accountForm"
                :rules="accountRules"
                layout="vertical"
                @finish="updateAccount"
                ref="accountFormRef"
              >
                <a-form-item label="用户名" name="username">
                  <a-input v-model:value="accountForm.username" />
                </a-form-item>
                
                <a-form-item label="姓" name="first_name">
                  <a-input v-model:value="accountForm.first_name" />
                </a-form-item>
                
                <a-form-item label="名" name="last_name">
                  <a-input v-model:value="accountForm.last_name" />
                </a-form-item>
                
                <a-form-item label="邮箱" name="email">
                  <a-input v-model:value="accountForm.email" />
                </a-form-item>
                
                <a-form-item>
                  <a-button type="primary" html-type="submit" :loading="updating">
                    保存修改
                  </a-button>
                </a-form-item>
              </a-form>
            </a-card>
            
            <a-card title="修改密码" class="password-card">
              <a-form
                :model="passwordForm"
                :rules="passwordRules"
                layout="vertical"
                @finish="updatePassword"
                ref="passwordFormRef"
              >
                <a-form-item label="当前密码" name="current_password">
                  <a-input-password v-model:value="passwordForm.current_password" />
                </a-form-item>
                
                <a-form-item label="新密码" name="new_password">
                  <a-input-password v-model:value="passwordForm.new_password" />
                </a-form-item>
                
                <a-form-item label="确认新密码" name="confirm_password">
                  <a-input-password v-model:value="passwordForm.confirm_password" />
                </a-form-item>
                
                <a-form-item>
                  <a-button type="primary" html-type="submit" :loading="updatingPassword">
                    修改密码
                  </a-button>
                </a-form-item>
              </a-form>
            </a-card>
          </a-tab-pane>
          
          <a-tab-pane key="subscription" tab="订阅管理">
            <a-card v-if="currentSubscription">
              <h3>当前订阅</h3>
              <a-descriptions bordered>
                <a-descriptions-item label="会员方案">
                  {{ currentSubscription.pricing_plan.name }}
                </a-descriptions-item>
                <a-descriptions-item label="开始日期">
                  {{ formatDate(currentSubscription.start_date) }}
                </a-descriptions-item>
                <a-descriptions-item label="到期日期">
                  {{ formatDate(currentSubscription.end_date) }}
                </a-descriptions-item>
                <a-descriptions-item label="自动续费">
                  {{ currentSubscription.auto_renew ? '是' : '否' }}
                </a-descriptions-item>
                <a-descriptions-item label="提示词上限">
                  {{ currentSubscription.pricing_plan.prompt_limit }}
                </a-descriptions-item>
              </a-descriptions>
              
              <div class="subscription-actions">
                <a-button 
                  type="primary" 
                  @click="router.push('/pricing')"
                >
                  升级会员
                </a-button>
                <a-button 
                  v-if="currentSubscription.auto_renew" 
                  danger 
                  @click="cancelAutoRenew"
                  :loading="cancelling"
                >
                  取消自动续费
                </a-button>
              </div>
            </a-card>
            <a-empty v-else description="您还没有订阅会员">
              <template #description>
                <span>您还没有订阅会员</span>
              </template>
              <a-button type="primary" @click="router.push('/pricing')">
                立即订阅
              </a-button>
            </a-empty>
            
            <a-card title="支付历史" class="payment-card">
              <a-table
                :dataSource="paymentHistory"
                :columns="paymentColumns"
                :pagination="{ pageSize: 5 }"
                :loading="loadingPayments"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'status'">
                    <a-tag :color="getPaymentStatusColor(record.status)">
                      {{ getPaymentStatusText(record.status) }}
                    </a-tag>
                  </template>
                </template>
              </a-table>
            </a-card>
          </a-tab-pane>
        </a-tabs>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { useAuthStore } from '../store/auth';
import { usePromptStore } from '../store/prompt';
import { useSubscriptionStore } from '../store/subscription';
import UserSubscriptionInfo from '../components/UserSubscriptionInfo.vue';
import { updateUserInfo, changePassword } from '../api/auth';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';

export default {
  name: 'ProfilePage',
  components: {
    UserSubscriptionInfo
  },
  setup() {
    const router = useRouter();
    const authStore = useAuthStore();
    const promptStore = usePromptStore();
    const subscriptionStore = useSubscriptionStore();
    
    const activeTab = ref('account');
    const accountFormRef = ref(null);
    const passwordFormRef = ref(null);
    const updating = ref(false);
    const updatingPassword = ref(false);
    const cancelling = ref(false);
    const loadingPayments = ref(false);
    const promptStats = ref(null);
    
    const user = computed(() => authStore.user);
    const userFullName = computed(() => authStore.userFullName);
    const currentSubscription = computed(() => subscriptionStore.currentSubscription);
    const daysRemaining = computed(() => subscriptionStore.daysRemaining);
    const paymentHistory = computed(() => subscriptionStore.paymentHistory);
    
    const accountForm = reactive({
      username: '',
      first_name: '',
      last_name: '',
      email: ''
    });
    
    const passwordForm = reactive({
      current_password: '',
      new_password: '',
      confirm_password: ''
    });
    
    const accountRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
      ]
    };
    
    const passwordRules = {
      current_password: [
        { required: true, message: '请输入当前密码', trigger: 'blur' }
      ],
      new_password: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 8, message: '密码长度不能少于8个字符', trigger: 'blur' }
      ],
      confirm_password: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
          validator: (_, value) => {
            if (value !== passwordForm.new_password) {
              return Promise.reject('两次输入的密码不一致');
            }
            return Promise.resolve();
          },
          trigger: 'blur'
        }
      ]
    };
    
    const paymentColumns = [
      {
        title: '支付日期',
        dataIndex: 'created_at',
        key: 'created_at',
        render: (text) => formatDate(text)
      },
      {
        title: '金额',
        dataIndex: 'amount',
        key: 'amount',
        render: (text) => `¥${text}`
      },
      {
        title: '支付方式',
        dataIndex: 'payment_method',
        key: 'payment_method',
        render: (text) => text === 'alipay' ? '支付宝' : '微信支付'
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status'
      }
    ];
    
    const initAccountForm = () => {
      if (!user.value) return;
      
      accountForm.username = user.value.username || '';
      accountForm.first_name = user.value.first_name || '';
      accountForm.last_name = user.value.last_name || '';
      accountForm.email = user.value.email || '';
    };
    
    const loadPromptStats = async () => {
      try {
        const stats = await promptStore.fetchPromptStats();
        promptStats.value = stats;
      } catch (error) {
        console.error('获取提示词统计信息失败:', error);
      }
    };
    
    const loadSubscriptionData = async () => {
      try {
        await subscriptionStore.fetchCurrentSubscription();
      } catch (error) {
        console.error('获取订阅信息失败:', error);
      }
    };
    
    const loadPaymentHistory = async () => {
      loadingPayments.value = true;
      try {
        await subscriptionStore.fetchPaymentHistory();
      } catch (error) {
        console.error('获取支付历史失败:', error);
      } finally {
        loadingPayments.value = false;
      }
    };
    
    const updateAccount = async () => {
      try {
        updating.value = true;
        
        const userData = {
          username: accountForm.username,
          first_name: accountForm.first_name,
          last_name: accountForm.last_name,
          email: accountForm.email
        };
        
        await updateUserInfo(userData);
        await authStore.fetchCurrentUser();
        message.success('账号信息更新成功');
      } catch (error) {
        message.error('更新账号信息失败');
        console.error(error);
      } finally {
        updating.value = false;
      }
    };
    
    const updatePassword = async () => {
      try {
        updatingPassword.value = true;
        
        await changePassword({
          old_password: passwordForm.current_password,
          new_password: passwordForm.new_password
        });
        
        message.success('密码修改成功');
        passwordFormRef.value.resetFields();
      } catch (error) {
        message.error('密码修改失败，请检查当前密码是否正确');
        console.error(error);
      } finally {
        updatingPassword.value = false;
      }
    };
    
    const cancelAutoRenew = async () => {
      if (!currentSubscription.value) return;
      
      cancelling.value = true;
      try {
        await subscriptionStore.cancelSubscriptionAutoRenew();
        message.success('已取消自动续费');
      } catch (error) {
        message.error('取消自动续费失败');
        console.error(error);
      } finally {
        cancelling.value = false;
      }
    };
    
    const getSubscriptionColor = () => {
      if (!currentSubscription.value) return 'default';
      
      const plan = currentSubscription.value.pricing_plan;
      if (plan.name.includes('高级')) return 'gold';
      if (plan.name.includes('专业')) return 'blue';
      return 'green';
    };
    
    const getPaymentStatusColor = (status) => {
      switch (status) {
        case 'success': return 'success';
        case 'pending': return 'warning';
        case 'failed': return 'error';
        default: return 'default';
      }
    };
    
    const getPaymentStatusText = (status) => {
      switch (status) {
        case 'success': return '支付成功';
        case 'pending': return '处理中';
        case 'failed': return '支付失败';
        default: return '未知状态';
      }
    };
    
    const formatDate = (dateString) => {
      try {
        return format(new Date(dateString), 'yyyy-MM-dd HH:mm', { locale: zhCN });
      } catch (e) {
        return dateString;
      }
    };
    
    onMounted(() => {
      if (!authStore.isAuthenticated) {
        router.push('/auth/login?redirect=/profile');
        return;
      }
      
      initAccountForm();
      loadPromptStats();
      loadSubscriptionData();
      loadPaymentHistory();
    });
    
    return {
      router,
      activeTab,
      accountFormRef,
      passwordFormRef,
      user,
      userFullName,
      accountForm,
      passwordForm,
      accountRules,
      passwordRules,
      updating,
      updatingPassword,
      cancelling,
      loadingPayments,
      promptStats,
      currentSubscription,
      daysRemaining,
      paymentHistory,
      paymentColumns,
      updateAccount,
      updatePassword,
      cancelAutoRenew,
      getSubscriptionColor,
      getPaymentStatusColor,
      getPaymentStatusText,
      formatDate
    };
  }
};
</script>

<style scoped>
.profile-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem 1rem;
}

.profile-card {
  height: 100%;
}

.profile-header {
  text-align: center;
  margin-bottom: 1.5rem;
}

.profile-header h2 {
  margin-top: 1rem;
  margin-bottom: 0.5rem;
}

.profile-header p {
  color: rgba(0, 0, 0, 0.45);
  margin-bottom: 0.5rem;
}

.profile-stats {
  display: flex;
  justify-content: space-around;
  text-align: center;
  margin-bottom: 1.5rem;
}

.stat-item {
  flex: 1;
}

.stat-value {
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--primary-color);
  margin-bottom: 0.25rem;
}

.stat-label {
  color: rgba(0, 0, 0, 0.45);
}

.password-card,
.payment-card {
  margin-top: 1.5rem;
}

.subscription-actions {
  display: flex;
  justify-content: flex-start;
  gap: 1rem;
  margin-top: 1.5rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-stats {
    flex-direction: column;
    gap: 1rem;
  }
}
</style>